#include "voice_receive.h"
#include "driver_gpio.h"
#include "driver_uart_ex.h"
#include "Motor.h"
#include "sys_utils.h"
#include "string.h"

uint8_t Voice_cmd_buff[8]={0};
uint8_t light_flag=0;

GPIO_InitTypeDef    GPIO_Handle;
UART_HandleTypeDef  Uart0_handle;

void uart_Init()
{
    __SYSTEM_UART0_CLK_ENABLE();
    GPIO_Handle.Pin       = GPIO_PIN_0|GPIO_PIN_1;
    GPIO_Handle.Mode      = GPIO_MODE_AF_PP;
    GPIO_Handle.Pull      = GPIO_PULLUP;
    GPIO_Handle.Alternate = GPIO_FUNCTION_4;
    gpio_init(GPIO_A, &GPIO_Handle);

    Uart0_handle.UARTx = Uart0;
    Uart0_handle.Init.BaudRate   = 9600;
    Uart0_handle.Init.DataLength = UART_DATA_LENGTH_8BIT;
    Uart0_handle.Init.StopBits   = UART_STOPBITS_1;
    Uart0_handle.Init.Parity     = UART_PARITY_NONE;
    Uart0_handle.Init.FIFO_Mode  = UART_FIFO_ENABLE;
    
    uart_init_ex(&Uart0_handle);
    NVIC_EnableIRQ(UART0_IRQn);
    NVIC_SetPriority(UART0_IRQn, 0);
    
}
void uart_receive_cmd()
{          
        uart_receive_IT(&Uart0_handle, Voice_cmd_buff, 8);
        while(Uart0_handle.b_RxBusy);       
        uart_transmit_IT(&Uart0_handle, Voice_cmd_buff, 8);
        while(Uart0_handle.b_TxBusy);       
}
void voice_cmd_handle()
{
    if(Voice_cmd_buff[5]==OPEN_LIGHT&&Voice_cmd_buff[6]==0x0E&&light_flag==0)
    {
        motor_forward();
        co_delay_100us(3000);
        motor_stop();
        light_flag=1;
    }

    if(Voice_cmd_buff[5]==CLOSE_LIGHT&&Voice_cmd_buff[6]==0x0F&&light_flag==1)
    {
        motor_reverse();
        co_delay_100us(3000);
        motor_stop();
        light_flag=0;
    }
    memset(Voice_cmd_buff,0,sizeof(Voice_cmd_buff));
}

void uart0_isr(void)
{
    uart_IRQHandler(&Uart0_handle);
}

